package com.itheima.interceptor;

import com.itheima.common.context.BaseContext;
import com.itheima.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        HandlerMethod handlerMethod =   (HandlerMethod)handler;
        log.info("当前拦截的方法为: {}",handlerMethod.getMethod().getName());
        log.info("当前拦截的方法参数长度为: {}",handlerMethod.getMethod().getParameters().length);
        log.info("当前拦截的方法为: {}",handlerMethod.getBean().getClass().getName());
        /**
         * 从请求头中获取token,并解析
         * authentication 前台传输过来的参数名称，不能变，要和前台保持一致
         */
        String authentication = request.getHeader("Token");
        if(authentication.isEmpty()||authentication == null){
            response.setStatus(401);
            return false;
        }
        //校验token
        try {
            Claims claimsBody = JwtUtil.getClaimsBody(authentication);
            int i = JwtUtil.verifyToken(claimsBody);
            if(i == 0||i==-1){
                String id = (String)claimsBody.get("id");
                BaseContext.setCurrentId(id);
                return true;
            }else{
                // 表示过期了
                //设置401
                //如果有登录数据，代表一登录，放行
                //否则，发送未认证错误信息
                response.setStatus(401);
                return false;
            }
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }



    }
}
